package edu.hawaii.myisern.action;

import java.io.File;

import edu.hawaii.myisern.appconfig.jaxb.AppConfig;
import edu.hawaii.myisern.model.IsernManager;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.util.Log;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.ValidationError;

/**
 * Reload all the application data from the xml file, 
 * call with http://127.0.0.1:8080/myisern-purple/Reload.action?key=purple.
 * @author Kevin English
 *
 */
public class ReloadActionBean extends IsernActionBean {

  protected static Log log = Log.getInstance(IsernActionBean.class);
  private String key = "";
  /**
   * Set key.
   * 
   * @param key the Key value.
   */
  public void setKey(String key) {
    this.key = key;
  }
  
  /**
   * Get the key.
   * @return the key value.
   */
  public String getKey() {
    return this.key;
  }
  /**
   * Reload the application if the proper key was sent.
   * @return The next appropriate jsp page.
   * @throws Exception If error occurs
   */
  @DefaultHandler
  @SuppressWarnings("PMD.ConfusingTernary")
  public Resolution reload() throws Exception {
    if (key != null) { 
      if ("test".equals(key)) {
        IsernManager.setDataDirectory(".myisern/test");
        AppConfig appConfig = IsernManager.loadAppConfig(IsernManager.getApplicationDirectory()
            + File.separatorChar + "appconfig.test.xml");
        IsernManager.loadApplication(appConfig);
        log.info("------- APPLICATION WAS RELOADED TO TEST MODEL-----------");
      }
      else if ("data".equals(key)) {
        IsernManager.loadApplication();
        log.info("------- APPLICATION WAS RELOADED TO NORMAL DATA-----------");
      }
    }
    else {
      ValidationError error = new SimpleError("Invalid reload key.");
      getContext().getValidationErrors().add("key", error);
      return new RedirectResolution("/reload.jsp");      
    }
    return new RedirectResolution("/reload.jsp");
  }
}
